package com.fedorvlasov.lazylist;



import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.util.ArrayList;




import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import androidstore.app.data.AppData;
import androidstore.app.data.AppFetcher;
import androidstore.app.data.ReviewData;

import com.paypal.android.MEP.CheckoutButton;
import com.paypal.android.MEP.PayPal;
import com.paypal.android.MEP.PayPalActivity;
import com.paypal.android.MEP.PayPalAdvancedPayment;
import com.paypal.android.MEP.PayPalInvoiceData;
import com.paypal.android.MEP.PayPalInvoiceItem;
import com.paypal.android.MEP.PayPalPayment;
import com.paypal.android.MEP.PayPalPreapproval;
import com.paypal.android.MEP.PayPalReceiverDetails;

public class AppActivity extends Activity implements OnClickListener{
	public static AppData appdata = null;
    private TextView description;
    private ImageView imgScreenshot;
    //private TextView linhvuc;
    private TextView price;
    private Button button;
    private static final int server = PayPal.ENV_SANDBOX;
	private static final String appID = "APP-80W284485P519543T";
	private static final int request = 1;
	private AppFetcher fetcher;
	private ListView list_Review;
	private ArrayList<ReviewData> ReviewList;
	private ReviewAdapter adapter;
	@Override
	public void onCreate(Bundle savedInstanceState){
    	super.onCreate(savedInstanceState);
    	
    	fetcher = new AppFetcher();
    	setContentView(R.layout.appdetail);
    	TextView appName = (TextView)findViewById(R.id.appName);
    	appName.setText(appdata.AppName);
    	this.button = (Button)findViewById(R.id.btnDownload);
    	
    	this.button.setOnClickListener(this);
        ImageView imgIcon =(ImageView)findViewById(R.id.imgIcon);
        String imgIconUrl =  appdata.linkIcon;
        Drawable drawableIcon = LoadImageFromWebOperations(imgIconUrl);
        imgIcon.setImageDrawable(drawableIcon);   
        
        this.imgScreenshot =(ImageView)findViewById(R.id.imgScreenshot);
        String imgScreenshotUrl =  this.appdata.linkScreenShot;
        Drawable drawableScreenshot = LoadImageFromWebOperations(imgScreenshotUrl);
        ReviewList = fetcher.getReview(appdata.id,1);
        list_Review=(ListView)findViewById(R.id.listReview);
        adapter=new ReviewAdapter(this, ReviewList);
        list_Review.setAdapter(adapter);         
        
        
        this.imgScreenshot.setImageDrawable(drawableScreenshot); 
        this.description = (TextView) findViewById(R.id.txtDescription);
        this.description.setText(appdata.Description);
        this.price = (TextView) findViewById(R.id.txtPrice);
        if (appdata.Price > 0.0f){
        	this.price.setText("$"+ appdata.Price);
        	this.button.setText("Buy");
        }
        else {
        	this.price.setText("FREE");
        	this.button.setText("Download");
        }
        
       /* Thread libraryInitializationThread = new Thread() {
    			public void run() {
    				initLibrary();
    				}
    		};
    		
    		libraryInitializationThread.start();   */
	}
	
	@Override
	public void onClick(View v) {
		if(appdata.Price > 0.0f)
		{
			initLibrary();
			// Use our helper function to create the simple payment.
			PayPalAdvancedPayment payment = exampleParallelPayment();
			// Use checkout to create our Intent.
			Intent checkoutIntent = PayPal.getInstance().checkout(payment, this);
			// Use the android's startActivityForResult() and pass in our Intent. This will start the library.
	    	 startActivityForResult(checkoutIntent, request); 	 
		}
		else{
			Intent browse = new Intent( Intent.ACTION_VIEW , Uri.parse(appdata.linkSource));
			fetcher.Download(appdata.id);
			startActivity( browse );	
		}
		
	}

    private Drawable LoadImageFromWebOperations(String url)
    {
    	try
    	{
    		InputStream is = (InputStream) new URL(url).getContent();
    		Drawable d = Drawable.createFromStream(is, "src name");
    		return d;
    	}catch (Exception e) {
    		System.out.println("Exc="+e);
    		return null;
    	}
    }
    
    private PayPalPayment exampleSimplePayment() {
		// Create a basic PayPalPayment.
		PayPalPayment payment = new PayPalPayment();
		// Sets the currency type for this payment.
    	payment.setCurrencyType("USD");
    	// Sets the recipient for the payment. This can also be a phone number.
    	payment.setRecipient("abc@paypal.com");
    	// Sets the amount of the payment, not including tax and shipping amounts.
    	payment.setSubtotal(new BigDecimal(Float.toString(appdata.Price)));
    	// Sets the payment type. This can be PAYMENT_TYPE_GOODS, PAYMENT_TYPE_SERVICE, PAYMENT_TYPE_PERSONAL, or PAYMENT_TYPE_NONE.
    	payment.setPaymentType(PayPal.PAYMENT_TYPE_GOODS);
    	
    	// PayPalInvoiceData can contain tax and shipping amounts. It also contains an ArrayList of PayPalInvoiceItem which can
    	// be filled out. These are not required for any transaction.
    	PayPalInvoiceData invoice = new PayPalInvoiceData();
    	// Sets the tax amount.
    	//invoice.setTax(new BigDecimal("1.25"));
    	// Sets the shipping amount.
    	//invoice.setShipping(new BigDecimal("4.50"));
    	
    	// PayPalInvoiceItem has several parameters available to it. None of these parameters is required.
    	PayPalInvoiceItem item1 = new PayPalInvoiceItem();
    	// Sets the name of the item.
    	item1.setName(appdata.AppName);
    	// Sets the ID. This is any ID that you would like to have associated with the item.
    	item1.setID(Integer.toString(appdata.id));
    	// Sets the total price which should be (quantity * unit price). The total prices of all PayPalInvoiceItem should add up
    	// to less than or equal the subtotal of the payment.
    	item1.setTotalPrice(new BigDecimal(Float.toString(appdata.Price)));
    	// Sets the unit price.
    	item1.setUnitPrice(new BigDecimal(Float.toString(appdata.Price)));
    	// Sets the quantity.
    	item1.setQuantity(1);
    	// Add the PayPalInvoiceItem to the PayPalInvoiceData. Alternatively, you can create an ArrayList<PayPalInvoiceItem>
    	// and pass it to the PayPalInvoiceData function setInvoiceItems().
    	invoice.getInvoiceItems().add(item1);
    	
    
    	
    	// Sets the PayPalPayment invoice data.
    	payment.setInvoiceData(invoice);
    	// Sets the merchant name. This is the name of your Application or Company.
    	payment.setMerchantName("AndroidStore");
    	// Sets the description of the payment.
    	payment.setDescription("buy application");
    	// Sets the Custom ID. This is any ID that you would like to have associated with the payment.
    	payment.setCustomID("8873482296");
    	// Sets the Instant Payment Notification url. This url will be hit by the PayPal server upon completion of the payment.
    	payment.setIpnUrl("http://www.exampleapp.com/ipn");
    	// Sets the memo. This memo will be part of the notification sent by PayPal to the necessary parties.
    	payment.setMemo("Hi! I'm making a memo for a simple payment.");
    	
    	return payment;
	}
    
    private PayPalAdvancedPayment exampleParallelPayment() {
    	double sys = appdata.Price * 0.2;
		double dev = appdata.Price - sys;
	
		PayPalAdvancedPayment payment = new PayPalAdvancedPayment();
		payment.setCurrencyType("USD");
		payment.setIpnUrl("http://www.exampleapp.com/ipn");
    	payment.setMemo("This sure is a swell memo for a parallel payment.");
    	
		PayPalReceiverDetails receiver1 = new PayPalReceiverDetails();
		receiver1.setRecipient("AndroidStore@gmail.com");
		receiver1.setSubtotal(new BigDecimal(sys));
		receiver1.setIsPrimary(false);
		receiver1.setPaymentType(PayPal.PAYMENT_TYPE_GOODS);
		PayPalInvoiceData invoice1 = new PayPalInvoiceData();
	
		PayPalInvoiceItem item1 = new PayPalInvoiceItem();
		item1.setName(appdata.AppName);
    	item1.setTotalPrice(new BigDecimal(sys));
    	invoice1.getInvoiceItems().add(item1);
    	receiver1.setInvoiceData(invoice1);
    	receiver1.setMerchantName("AndroisStore");
    	receiver1.setDescription("Pay the Store");
    	payment.getReceivers().add(receiver1);
    	
    	// Create another receiver for the parallel payment
		PayPalReceiverDetails receiver2 = new PayPalReceiverDetails();
		receiver2.setRecipient(appdata.PaypalAccount);
		receiver2.setSubtotal(new BigDecimal(dev));
		receiver2.setIsPrimary(false);
		receiver2.setPaymentType(PayPal.PAYMENT_TYPE_GOODS);
		
		
		PayPalInvoiceData invoice2 = new PayPalInvoiceData();
		PayPalInvoiceItem item2 = new PayPalInvoiceItem();
		// Sets the name of the item.
    	item2.setName(appdata.AppName);
    	item2.setTotalPrice(new BigDecimal(dev));
    	invoice2.getInvoiceItems().add(item2);
    	
    	receiver2.setInvoiceData(invoice2);
    	receiver2.setMerchantName("Developer");
    	receiver2.setDescription("Pay for Developer");
    	payment.getReceivers().add(receiver2);
    	return payment;
	}
    
    private void initLibrary() {
		PayPal pp = PayPal.getInstance();
		// If the library is already initialized, then we don't need to initialize it again.
		if(pp == null) {
			// This is the main initialization call that takes in your Context, the Application ID, and the server you would like to connect to.
			pp = PayPal.initWithAppID(this, appID, server);
			// -- These are required settings.
        	pp.setLanguage("en_US"); // Sets the language for the library.
        
        	pp.setFeesPayer(PayPal.FEEPAYER_EACHRECEIVER); 
        	// Set to true if the transaction will require shipping.
        	pp.setShippingEnabled(true);
        	// Dynamic Amount Calculation allows you to set tax and shipping amounts based on the user's shipping address. Shipping must be
        	// enabled for Dynamic Amount Calculation. This also requires you to create a class that implements PaymentAdjuster and Serializable.
        	pp.setDynamicAmountCalculationEnabled(false);
        	// --
		}
	}
	
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data )
    {
    	switch(resultCode)
    	{
    		case Activity.RESULT_OK:
    			//String payKey = 
    			//	data.getStringExtra(PayPalActivity.EXTRA_PAY_KEY);
    			Intent browse = new Intent( Intent.ACTION_VIEW , Uri.parse(appdata.linkSource));
    			 fetcher.Download(appdata.id);
     	 		startActivity(browse);
    			break;
    		case Activity.RESULT_CANCELED:
    			break;
    		case PayPalActivity.RESULT_FAILURE:
    			String errorID = data.getStringExtra(PayPalActivity.EXTRA_ERROR_ID); 
    			String errorMessage = data.getStringExtra(PayPalActivity.EXTRA_ERROR_MESSAGE); 
    	}
    }
    
}
